#!/usr/bin/python3
from openpyxl import load_workbook
import os, gc
from .Base_Plugin import Base_Plugin


class Sheet_Clear_Table_NotIn_Directory(Base_Plugin):
    """清理无效工作表插件"""

    def __init__(self, context) -> None:
        super().__init__()
        self.context = context
        self.inside_sheets = self.context["inside_sheets"]

    def run(self, workspace, source):
        workbook = load_workbook(os.path.join(workspace, source))
        _directory = workbook["目录"]
        based_on = list()
        for row in _directory.rows:
            table_name = row[2].value
            if table_name != "描述" and table_name is not None:
                based_on.append(table_name.strip())
        for sheet_name in workbook.sheetnames:
            if sheet_name not in self.inside_sheets and sheet_name not in based_on:
                del workbook[sheet_name]
                self.processed += 1
        return_val = None
        if self.processed > 0:
            saved_name = r"ClearTableNotInDirectory.xlsx"
            new_path = os.path.join(workspace, saved_name)
            if os.path.exists(new_path):
                os.remove(new_path)
            workbook.save(new_path)
            return_val = saved_name
        else:
            return_val = source
        del workbook
        gc.collect()
        return return_val
